package com.example.anew.journey.mynewjourney.firstchangelogic.personalInformation.persenter;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.example.anew.journey.mynewjourney.R;
import com.example.anew.journey.mynewjourney.base.MyApplication;
import com.example.anew.journey.mynewjourney.bean.TakeDateBean;
import com.example.anew.journey.mynewjourney.config.RBConstants;
import com.example.anew.journey.mynewjourney.firstchangelogic.personalInformation.bean.BirthdayBean;
import com.example.anew.journey.mynewjourney.firstchangelogic.personalInformation.bean.HeadPortraitBean;
import com.example.anew.journey.mynewjourney.firstchangelogic.personalInformation.bean.InitInformationDateBean;
import com.example.anew.journey.mynewjourney.firstchangelogic.personalInformation.bean.NicknameBean;
import com.example.anew.journey.mynewjourney.firstchangelogic.personalInformation.bean.PersonalInformationBean;
import com.example.anew.journey.mynewjourney.firstchangelogic.personalInformation.model.FirstChangePersonalInformationModel;
import com.example.anew.journey.mynewjourney.firstchangelogic.personalInformation.model.ISFirstChangePersonalInformationModel;
import com.example.anew.journey.mynewjourney.firstchangelogic.personalInformation.view.FirstChangePersonalInformationView;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.jesse.nativelogger.NLogger;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 杭州惟君医疗科技有限公司18
 * Created by 20433 on 2018/3/15
 */

public class FirstChangePersonalInformationPersenter {
    private FirstChangePersonalInformationView mFirstChangePersonalInformationView;
    private ISFirstChangePersonalInformationModel mISFirstChangePersonalInformationModel;
    private PopupWindow mPopWindowHeadPortrait;
    private PopupWindow mPopWindowNickname;
    private PopupWindow mPopWindowNickname1;
    private String user_id;
    private String token;
    private final SimpleDateFormat time;

    public FirstChangePersonalInformationPersenter(FirstChangePersonalInformationView isFirstChangePersonalInformationView) {
        this.mFirstChangePersonalInformationView = isFirstChangePersonalInformationView;
        mISFirstChangePersonalInformationModel = new FirstChangePersonalInformationModel();
        time = new SimpleDateFormat("yyyy年MM月dd日");
    }
    //点击头像
    public void onClickeHeadPortrait(Context mcontext){
        //PopupImageSelection(mcontext);
        mFirstChangePersonalInformationView.toImageSelection();

    }

    private void PopupImageSelection(Context mcontext) {
        //设置contentView
        View contentView = LayoutInflater.from(mcontext).inflate(R.layout.personal_information_head_portrait_popu, null);
        mPopWindowHeadPortrait = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        mPopWindowHeadPortrait.setContentView(contentView);
        mFirstChangePersonalInformationView.findHeadOptionsView(contentView);
        mPopWindowHeadPortrait.setFocusable(true);
        mPopWindowHeadPortrait.setAnimationStyle(R.style.mypopwindow_anim_style);
        //显示PopupWindow
        View rootview = LayoutInflater.from(mcontext).inflate(R.layout.activity_first_change_personal_information, null);
        mPopWindowHeadPortrait.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
    }

    //点击昵称
    public  void  onClickeNickname(Context mcontext){
//设置contentView
        View contentView = LayoutInflater.from(mcontext).inflate(R.layout.personal_information_nickname_popu, null);
        mPopWindowNickname1 = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        mPopWindowNickname1.setContentView(contentView);
        mFirstChangePersonalInformationView.findInputNicknameView(contentView);
        //显示PopupWindow
        View rootview = LayoutInflater.from(mcontext).inflate(R.layout.activity_first_change_personal_information, null);
        mPopWindowNickname1.showAtLocation(rootview, Gravity.CENTER, 0, 0);
    }
    //点击生日
    public  void onClickeBirthday(final Context mcontext){
        DatePickDialog dialog = new DatePickDialog(mcontext);
        //设置上下年分限制
        dialog.setYearLimt(5);
        //设置标题
        dialog.setTitle("选择时间");
        //设置类型
        dialog.setType(DateType.TYPE_YMD);
        //设置消息体的显示格式，日期格式
        dialog.setMessageFormat("yyyy-MM-dd");
        //设置选择回调
        dialog.setOnChangeLisener(null);
        //设置点击确定按钮回调
        dialog.setOnSureLisener(new OnSureLisener() {
            @Override
            public void onSure(Date date) {

                mFirstChangePersonalInformationView.setBirthday(date);
                submitBirthday(time.format(date),user_id,mcontext);
               // mISFirstChangePersonalInformationModel.StoreBirthday(time.format(date),mcontext);
            }

        });
        dialog.show();
    }
    public String ForBirthday(Context mcontext){
        PersonalInformationBean penson =  mISFirstChangePersonalInformationModel.TakePersonalInformation(mcontext);
        String birthday = penson.getDate();
        NLogger.e("TAG","============NetworkResponseDate==34==============="+birthday);
        if(!TextUtils.isEmpty(birthday)){
            return birthday;
        }
        return "0";
    }
    //点击头像选框的 取消按钮
    public void  onClickeHeadPortraitOptionsCancel(){
        CancelOnClickeHeadPortraitPopupWindow();
    }
    //点击头像选框的 拍照按钮
    public void onClickeHeadPortraitOptionTakingPictures(){
        CancelOnClickeHeadPortraitPopupWindow();
    }
    //点击头像选框的 从手机相册选择按钮
    public void onClickeHeadPortraitOptionChooseFromYourPhoneAlbum(){
        CancelOnClickeHeadPortraitPopupWindow();
    }
    //点击昵称选框的 取消按钮
    public void  onClickeNicknameOptionsCancel(){
        CancelOnClickeNicknamePopupWindow();

    }
    //点击昵称选框的 保存按钮
    public void  onClickeNicknameOptionsSave(Context mcontext){
       String str =  mFirstChangePersonalInformationView.getInputNickname();
        if(TextUtils.isEmpty(str)) mFirstChangePersonalInformationView.showToastInformation("请输入昵称");
        mFirstChangePersonalInformationView.setNickname(str);

        submitNickname(str,mcontext,user_id);
        CancelOnClickeNicknamePopupWindow();
    }

    //取消点击头像PopupWindow
    public void CancelOnClickeHeadPortraitPopupWindow(){
        mPopWindowHeadPortrait.dismiss();
    }
    //取消点击昵称PopupWindow
    public void CancelOnClickeNicknamePopupWindow(){
        mPopWindowNickname1.dismiss();
    }
    // 取出 头像 昵称 生日
    public void  getPersonalInformation(Context mcontext){
        PersonalInformationBean personalInformationBean = mISFirstChangePersonalInformationModel.TakePersonalInformation(mcontext);
        mFirstChangePersonalInformationView.setHeadPortrait(personalInformationBean.getUrl());
        mFirstChangePersonalInformationView.setNickname(personalInformationBean.getNickname());
        mFirstChangePersonalInformationView.setBirthdayOne(personalInformationBean.getDate());
    }



    public void  initInformation(Context mcontext){
        TakeDateBean bean = mISFirstChangePersonalInformationModel.TakeDate(mcontext);
        user_id = bean.getUser_id();
        token = bean.getToken();
        if(TextUtils.isEmpty(user_id)){
            mFirstChangePersonalInformationView.showToastInformation("");
            return;
        }
        if(TextUtils.isEmpty(token)){
            mFirstChangePersonalInformationView.showToastInformation("");
            return;
        }
        submit(user_id, token,mcontext);

    }

    private void submit(String user_id, String token, final Context mcontext) {
        String url = RBConstants.SERVER_URL+RBConstants.INFORMATION;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                        NLogger.e("TAG","============NetworkResponseDate==324==============="+NetworkResponseDate);
                        final InitInformationDateBean mInitInformationDateBean =   gson.fromJson(NetworkResponseDate, InitInformationDateBean.class);
                                if(mInitInformationDateBean.errorCode == 200){
                                    InitInformationDateBean.DataBean bean =     mInitInformationDateBean.data;
                                    if(bean != null) {
                                        mISFirstChangePersonalInformationModel.saveDate(bean,mcontext);
                                        mFirstChangePersonalInformationView.setHeadPortrait(bean.cus_logo);
                                        mFirstChangePersonalInformationView.setNickname(bean.cus_name);
                                        mFirstChangePersonalInformationView.setBirthdayOne(bean.birthday);
                                    }
                                }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                       // mFirstChangePersonalInformationView.showToastInformation("请查看网络");
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }


    private void submitNickname(final String str, final Context mcontext, String user_id) {
        String url = RBConstants.SERVER_URL+RBConstants.CHANGE_NINAME;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("cus_id",user_id)
                .addParams("cus_name", str)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                        //NLogger.e("TAG","============NetworkResponseDate================="+NetworkResponseDate);
                        final NicknameBean nicknameBean =   gson.fromJson(NetworkResponseDate, NicknameBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(nicknameBean.errorCode == 200){
                                    NicknameBean.DataBean bean = nicknameBean.data;
                                    if(bean != null){
                                        mFirstChangePersonalInformationView.setNickname(bean.cus_name);
                                        mFirstChangePersonalInformationView.showToastInformation("昵称修改成功");
                                        mISFirstChangePersonalInformationModel.storeNickname(bean.cus_name,mcontext);
                                    }
                                }else{
                                    mFirstChangePersonalInformationView.showToastInformation("昵称修改失败");
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                       // mFirstChangePersonalInformationView.showToastInformation("请查看网络");
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }


    private void submitBirthday(final String format, String user_id, final Context mcontext) {
        String url = RBConstants.SERVER_URL+RBConstants.CHANGE_BIRTHDAY;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("cus_id", user_id)
                .addParams("birthday",format)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                        NLogger.e("TAG","=====12=======NetworkResponseDate================="+NetworkResponseDate);
                        final BirthdayBean birthdayBean =   gson.fromJson(NetworkResponseDate, BirthdayBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(birthdayBean.errorCode == 200){
                                    BirthdayBean.DataBean bean =    birthdayBean.data;
                                    if(bean != null){
                                       // mFirstChangePersonalInformationView.setBirthdayOne(bean.birthday);
                                        mFirstChangePersonalInformationView.showToastInformation("生日更改成功");
                                        mISFirstChangePersonalInformationModel.StoreBirthday(format,mcontext);
                                    }
                                }else{
                                    mFirstChangePersonalInformationView.showToastInformation("生日更改失败");
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                       // mFirstChangePersonalInformationView.showToastInformation("请查看网络");
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }


    //上传头像
    public void submitHeadPortraitResources(String str, final Context mcontext){
        File file = new File(str);
        String url = RBConstants.SERVER_URL+RBConstants.CHANGE_HEAD_PORTRATIT;
        OkHttpUtils.post()//
                .addFile("cus_logo", file.getName(), file)//
                .url(url)
                .addParams("cus_id", user_id)
                .build()//
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                        //NLogger.e("TAG","============submitHeadPortraitResources================="+NetworkResponseDate);
                        final HeadPortraitBean headPortraitBean =   gson.fromJson(NetworkResponseDate, HeadPortraitBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(headPortraitBean.errorCode == 200){

                                    HeadPortraitBean.DataBean bean =   headPortraitBean.data;
                                    if(bean != null){
                                        mFirstChangePersonalInformationView.setHeadPortrait(bean.cus_logo);
                                        mFirstChangePersonalInformationView.showToastInformation("头像更改成功");
                                        mISFirstChangePersonalInformationModel.storeAvatarInformation(bean.cus_logo,mcontext);
                                    }
                                }else{
                                    mFirstChangePersonalInformationView.showToastInformation("头像上传失败");
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //mFirstChangePersonalInformationView.showToastInformation("请查看网络");
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }


}
